package com.leruan.aasimp.action.forum;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.leruan.aasimp.entity.Mainpost;
import com.leruan.aasimp.entity.Reply;
import com.leruan.aasimp.service.MainPostService;
import com.leruan.aasimp.service.ReplyService;
import com.leruan.aasimp.util.StringUtil;
import com.leruan.aasimp.util.Validators;
import com.opensymphony.xwork2.ActionSupport;

public class ReplyAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = -5795300115204528449L;

    @Resource
    private ReplyService replyService;
    @Resource
    private MainPostService mainPostService;

    public String reply() throws UnsupportedEncodingException {
        HttpServletRequest request = ServletActionContext.getRequest();
        String mainpostId = request.getParameter("postId");
        String boardId = request.getParameter("boardId");
        String userId = request.getParameter("userId");
        String replyId = StringUtil.getUUID();
        String replyContent = request.getParameter("replyContent");
        Date date = new Date();
        Reply reply = new Reply(replyId, mainpostId, userId, replyContent, date, 0l, boardId);
        validateReply(reply);
        if (hasErrors()) {
            return "success";
        }
        replyService.save(reply);
        Mainpost mainPost = mainPostService.getMainPostsByPostId(mainpostId);
        mainPost.setReplyNum(mainPost.getReplyNum() + 1);
        mainPost.setLastReplyUserId(userId);
        mainPost.setLastReplyDate(new Date());
        mainPostService.modifyMainPost(mainPost);
        request.setAttribute("postId", mainpostId);
        return "success";
    }

    private void validateReply(Reply reply) {
        if (Validators.isEmpty(reply.getReplyContent())) {
            addActionError("请说几句话在提交吧！");
        }
    }

    public ReplyService getReplyService() {
        return replyService;
    }

    public void setReplyService(ReplyService replyService) {
        this.replyService = replyService;
    }

    public MainPostService getMainPostService() {
        return mainPostService;
    }

    public void setMainPostService(MainPostService mainPostService) {
        this.mainPostService = mainPostService;
    }

}
